#import "HistorySearchTagView.h"

#define kTagMargin 8.0f
#define kTagHeight 30.0f
#define kTagCornerRadius 15.0f
#define kTagTextPadding 12.0f
#define kDeleteButtonWidth 25.0f

@interface HistorySearchTagView ()

@property (nonatomic, strong) NSMutableArray<NSString *> *tags;
@property (nonatomic, assign) NSInteger maxTagCount;
@property (nonatomic, assign) BOOL isEditing;
@property (nonatomic, strong) UIButton *clearAllButton;

@end

@implementation HistorySearchTagView

- (instancetype)initWithFrame:(CGRect)frame maxTagCount:(NSInteger)maxCount {
    self = [super initWithFrame:frame];
    if (self) {
        _tags = [NSMutableArray array];
        _maxTagCount = maxCount;
        _isEditing = NO;
        
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    self.backgroundColor = [UIColor whiteColor];
    
    // 添加清空全部按钮
    _clearAllButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_clearAllButton setTitle:@"清空全部" forState:UIControlStateNormal];
    [_clearAllButton setTitleColor:[UIColor colorWithRed:0.2 green:0.6 blue:0.9 alpha:1.0] forState:UIControlStateNormal];
    _clearAllButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [_clearAllButton addTarget:self action:@selector(clearAllTagsAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_clearAllButton];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    // 布局清空全部按钮
    CGFloat clearButtonX = 20.0f;
    CGFloat clearButtonY = 5.0f;
    _clearAllButton.frame = CGRectMake(clearButtonX, clearButtonY, 70.0f, 20.0f);
    
    // 布局标签
    [self layoutTags];
}

- (void)layoutTags {
    // 移除所有标签视图
    for (UIView *subview in self.subviews) {
        if ([subview isKindOfClass:[UIView class]] && subview.tag >= 1000) {
            [subview removeFromSuperview];
        }
    }
    
    if (self.tags.count == 0) {
        return;
    }
    
    CGFloat currentX = kTagMargin;
    CGFloat currentY = 35.0f; // 留出顶部空间给清空按钮
    
    NSInteger displayCount = MIN(self.tags.count, self.maxTagCount);
    
    for (NSInteger i = 0; i < displayCount; i++) {
        NSString *tag = self.tags[i];
        
        // 计算标签宽度
        UILabel *tempLabel = [[UILabel alloc] init];
        tempLabel.text = tag;
        tempLabel.font = [UIFont systemFontOfSize:14.0f];
        [tempLabel sizeToFit];
        CGFloat textWidth = tempLabel.frame.size.width;
        
        CGFloat tagWidth = textWidth + kTagTextPadding * 2;
        if (self.isEditing) {
//            tagWidth += kDeleteButtonWidth;
        }
        
        // 如果当前行放不下，换行
        if (currentX + tagWidth + kTagMargin > self.bounds.size.width) {
            currentX = kTagMargin;
            currentY += kTagHeight + kTagMargin;
        }
        
        // 创建标签视图
        UIView *tagView = [[UIView alloc] initWithFrame:CGRectMake(currentX, currentY, tagWidth, kTagHeight)];
        tagView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
        tagView.layer.cornerRadius = kTagCornerRadius;
        tagView.layer.masksToBounds = YES;
        tagView.tag = 1000 + i;
        [self addSubview:tagView];
        
        // 添加标签文本
        UILabel *tagLabel = [[UILabel alloc] initWithFrame:CGRectMake(kTagTextPadding, 0, textWidth, kTagHeight)];
        tagLabel.text = tag;
        tagLabel.font = [UIFont systemFontOfSize:14.0f];
        tagLabel.textColor = [UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:1.0];
        tagLabel.textAlignment = NSTextAlignmentCenter;
        [tagView addSubview:tagLabel];
        
        // 添加删除按钮
        if (self.isEditing) {
            UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
            deleteButton.frame = CGRectMake(tagWidth - kDeleteButtonWidth, 0, kDeleteButtonWidth, kTagHeight);
            [deleteButton setImage:[UIImage imageNamed:@"delete_icon"] forState:UIControlStateNormal];
            [deleteButton addTarget:self action:@selector(deleteTagAction:) forControlEvents:UIControlEventTouchUpInside];
            deleteButton.tag = i;
            [tagView addSubview:deleteButton];
            
            // 调整文本位置
            tagLabel.frame = CGRectMake(kTagTextPadding, 0, textWidth, kTagHeight);
        }
        
        // 添加点击手势
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tagTapped:)];
        tapGesture.numberOfTapsRequired = 1;
        [tagView addGestureRecognizer:tapGesture];
        
        // 更新当前X坐标
        currentX += tagWidth + kTagMargin;
    }
    
    // 更新视图高度
    CGFloat contentHeight = currentY + kTagHeight + kTagMargin;
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, contentHeight);
}

- (void)setTags:(NSArray<NSString *> *)tags {
    [self.tags removeAllObjects];
    [self.tags addObjectsFromArray:tags];
    [self setNeedsLayout];
}

- (void)addTag:(NSString *)tag {
    if (!tag || [tag length] == 0) {
        return;
    }
    
    // 移除已存在的相同标签
    [self.tags removeObject:tag];
    
    // 添加到最前面
    [self.tags insertObject:tag atIndex:0];
    
    // 如果超过最大数量，移除最后一个
    if (self.tags.count > self.maxTagCount) {
        [self.tags removeLastObject];
    }
    
    [self setNeedsLayout];
}

- (void)deleteTag:(NSString *)tag {
    [self.tags removeObject:tag];
    [self setNeedsLayout];
}

- (void)clearAllTags {
    [self.tags removeAllObjects];
    [self setNeedsLayout];
    
    if ([self.delegate respondsToSelector:@selector(didClearAllTags)]) {
        [self.delegate didClearAllTags];
    }
}

- (void)updateEditingState:(BOOL)isEditing {
    _isEditing = isEditing;
    [self setNeedsLayout];
}

- (NSArray<NSString *> *)getAllTags {
    return [self.tags copy];
}

#pragma mark - Action Methods

- (void)tagTapped:(UITapGestureRecognizer *)gesture {
    NSInteger index = gesture.view.tag - 1000;
    if (index >= 0 && index < self.tags.count) {
        NSString *tag = self.tags[index];
        if ([self.delegate respondsToSelector:@selector(didSelectTag:)]) {
            [self.delegate didSelectTag:tag];
        }
    }
}

- (void)deleteTagAction:(UIButton *)sender {
    NSInteger index = sender.tag;
    if (index >= 0 && index < self.tags.count) {
        NSString *tag = self.tags[index];
        [self.tags removeObjectAtIndex:index];
        
        // 更新所有删除按钮的tag
        [self updateDeleteButtonTagsAfterDeletionFromIndex:index];
        
        [self setNeedsLayout];
        
        if ([self.delegate respondsToSelector:@selector(didDeleteTag:newTags:)]) {
            [self.delegate didDeleteTag:tag newTags:[self.tags copy]];
        }
    }
}

- (void)updateDeleteButtonTagsAfterDeletionFromIndex:(NSInteger)deletedIndex {
    // 更新所有后续标签的删除按钮tag
    for (UIView *subview in self.subviews) {
        if ([subview isKindOfClass:[UIView class]] && subview.tag >= 1000 + deletedIndex + 1) {
            NSInteger originalTag = subview.tag - 1000;
            for (UIView *innerView in subview.subviews) {
                if ([innerView isKindOfClass:[UIButton class]]) {
                    UIButton *deleteButton = (UIButton *)innerView;
                    deleteButton.tag = originalTag - 1;
                    break;
                }
            }
        }
    }
}

- (void)clearAllTagsAction {
    [self clearAllTags];
}

@end
